package com.tang.Web;
import com.tang.Utils.JDBCUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class TranscationFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        resp.setContentType("text/html;charset=UTF-8");
        try {
            filterChain.doFilter(servletRequest,servletResponse);
            JDBCUtils.commitAndClose();
        }catch(Exception e){
            try {
                JDBCUtils.rollbackAndClose();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            System.out.println("出现异常");
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {

    }
}
